<template>
  <!-- 表单 -->
  <el-form inline="true">
    <el-form-item label="用户id">
      <el-input v-model="params.userId" placeholder="请您输入要搜索的用户id" />
    </el-form-item>
    <el-form-item label="账号">
      <el-input v-model="params.userAccount" placeholder="请您输入要搜索的账号" />
    </el-form-item>
    <el-form-item>
      <el-button @click="onSearch" plain>搜索</el-button>
      <el-button @click="onReset" plain type="info">重置</el-button>
      <el-button @click="showAddDialog = true" type="primary">添加管理员</el-button>
    </el-form-item>
  </el-form>
  <!-- 添加用户对话框 -->
  <el-dialog v-model="showAddDialog" title="添加用户" width="30%">
    <el-form :model="addForm" label-width="100px">
      <el-form-item label="用户账号">
        <el-input v-model="addForm.userAccount" placeholder="请输入用户账号" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="addForm.password" placeholder="请输入密码" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="onAddUser">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 表格 -->
  <el-table height="526px" :data="userList">
    <el-table-column prop="userId" label="用户id" width="180px" />
    <el-table-column prop="userAccount" label="账号" />
    <el-table-column prop="userName" label="用户名" />
  </el-table>
  <!-- 分页区域 -->
  <el-pagination background size="small" layout="total, sizes, prev, pager, next, jumper" :total="total"
    v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[5, 10, 15, 20]"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<script setup>
import { reactive, ref } from 'vue';
import { getSuserListService, addUserService } from '@/apis/suser'

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: '',
  userAccount: '',
  userName: '',
})

const userList = ref([])
const total = ref(0)
const showAddDialog = ref(false)

const addForm = reactive({
  userAccount: '',
  password: ''
})

async function getUserList() {
  const ref = await getSuserListService(params)
  console.log('完整响应:', ref)
  userList.value = ref.rows
  total.value = ref.total
}
getUserList()

function onSearch() {
  params.pageNum = 1
  getUserList()
}

function onReset() {
  params.pageNum = 1
  params.pageSize = 10
  params.userId = ''
  params.userAccount = ''
  getUserList()
}

function handleSizeChange(newSize) {
  params.pageNum = 1
  getUserList()
}

function handleCurrentChange(newPage) {
  getUserList()
}

async function onAddUser() {
  try {
    await addUserService(addForm)
    ElMessage.success('添加用户成功')
    showAddDialog.value = false
    // 重置表单
    addForm.userAccount = ''
    addForm.password = ''
    // 刷新用户列表
    getUserList()
  } catch (error) {
    ElMessage.error(error.message || '添加用户失败')
  }
}
</script>